package cn.acewill.yxd.yunxundian.ui.user;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.zyf.vc.ui.PlayVideoActiviy;
import com.zyf.vc.ui.RecorderActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.photoCrop.BitmapUtils;
import cn.acewill.yxd.yunxundian.componet.photoCrop.PopupUtil;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.sign.MarkPhotoActivity;
import cn.acewill.yxd.yunxundian.utils.PermissionUtil;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by xxx on 2018/1/19.
 */

public abstract class YxdAbstractPhtotoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    private final int REQUEST_CODE_GALLERY=1000;
    private final int REQUEST_CODE_CARMEAR=1001;
    private final int REQUEST_TAKE_VIDEO_CODE =1002 ;

    private boolean isMultiSelector=false;

    //拍照保存的路径
    private String allPhotoFileString="";
    private String newPhotoName = "";
    //照片最大数量
    private int maxJpgCount = 9;
    //视频的存储路径
    private String allVideoFileString="";

    private Dialog popDialog;
    private ProgressDialog waterDialog;
    /*最后生成的图片的路径*/
    private String resultPath;
    //水印门店的名称
    private String shopName;
    private Handler mHandler = new iHandler(this);



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager winManager = getWindowManager();
        DisplayMetrics metrics = new DisplayMetrics();
        winManager.getDefaultDisplay().getMetrics(metrics);
        methodRequiresPermission();
    }

    //图片拍照
    protected void showPopWin(Context context,String shopName,boolean isMultiSelector,int jpgCount){
        this.shopName = shopName;
        this.maxJpgCount = jpgCount;
        this.isMultiSelector = isMultiSelector;
        //清空上次的记录
        allPhotoFileString = "";
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (inflater!=null){
            View holder = inflater.inflate(R.layout.view_popup_button,
                    (ViewGroup) getWindow().getDecorView(), false);
            View gallery = holder.findViewById(R.id.btnPhoto);
            View capture = holder.findViewById(R.id.btnCapture);
            View cancel = holder.findViewById(R.id.btnCanel);

            ButtonClick click = new ButtonClick(this);
            gallery.setOnClickListener(click);// 图库选择
            capture.setOnClickListener(click);// 拍照选择
            cancel.setOnClickListener(click);// 取消
            popDialog= PopupUtil.makePopup(context,holder);
            popDialog.show();
        }
    }

    //视屏录制
    public void showVideoPop(Context context){
        LayoutInflater inflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        allVideoFileString = "";
        if (inflater!=null){
            View holder=inflater.inflate(R.layout.view_popup_button2,null,false);
            View cancle=holder.findViewById(R.id.btnCanel);
            View video=holder.findViewById(R.id.btnVideo);

            ButtonClick click = new ButtonClick(this);
            cancle.setOnClickListener(click);
            video.setOnClickListener(click);
            popDialog=PopupUtil.makePopup(this,holder);
            popDialog.show();
        }
    }

    public class ButtonClick implements View.OnClickListener {

        private Context context;

        private ButtonClick(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {


            if (popDialog != null) {
                popDialog.dismiss();
            }
            if (v.getId() == R.id.btnPhoto) {// 图库选取
                checkTakeMediaPermission(R.id.btnPhoto);
            }

            if (v.getId() == R.id.btnCapture) {// 拍照
                // 从相册选取
                checkTakeMediaPermission(R.id.btnCapture);
            }
			/*视频录制*/
            if (v.getId()==R.id.btnVideo){
                // TODO: 2017/5/10  videorecord
				/*
				1.判断权限
				2.跳转拍摄
				 */
                checkTakeMediaPermission(R.id.btnVideo);
            }
            if (v.getId()==R.id.btn_cancel){
                popDialog.dismiss();
            }
        }
    }
    /*权限的获取*/
    private void checkTakeMediaPermission(int typeid) {
        int permissionState_Camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int permissionState_Storage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionState_Audio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (permissionState_Camera != PackageManager.PERMISSION_GRANTED || permissionState_Storage != PackageManager.PERMISSION_GRANTED
                || permissionState_Audio != PackageManager.PERMISSION_GRANTED) {
            // 用户已经拒绝过一次，给用户解释提示对话框
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                // 展示自定义提醒框
                new MaterialDialog.Builder(this)
                        .content("你必须允许相应权限")
                        .positiveText("确定")
                        .positiveColor(getResources().getColor(R.color.blue))
                        .negativeText("取消")
                        .negativeColor(getResources().getColor(R.color.color_theme))
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                PermissionUtil.requestPermissionForCamera(YxdAbstractPhtotoActivity.this);
                            }

                        })
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .build()
                        .show();
            }else{
                PermissionUtil.requestPermissionForCamera(this);
            }
        }else{
            if(typeid==R.id.btnVideo)
                skipToVideoTaker();
            else if(typeid==R.id.btnCapture) {
                YXDAPP.GallerySet(maxJpgCount,this);
                GalleryFinal.openCamera(REQUEST_CODE_CARMEAR, YXDAPP.functionConfig, myResultCallBack);
            }
            else if(typeid==R.id.btnPhoto)
            {
                if (isMultiSelector){
                    YXDAPP.GallerySet(maxJpgCount,this);
                    GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }else{ //选取头像
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }
            }
        }
    }
    /*跳转到拍摄*/
    private void skipToVideoTaker(){
        startActivityForResult(new Intent(this, RecorderActivity.class),REQUEST_TAKE_VIDEO_CODE);
        getVideoPath();
    }

    public void getVideoPath() {
        PlayVideoActiviy.setOnPickFinishListener(new PlayVideoActiviy.PickFinishListener() {
            @Override
            public void onPickFinish(String path) {
                BaseActivity.showAnimaDialog(YxdAbstractPhtotoActivity.this,"视频保存在"+"\n"+path);
                Log.i("videoPath=", path);
            //    allVideoFileString+=path+",";
                allVideoFileString = path;
                onVideoRecode(allVideoFileString);
            }
        });
    }


    private GalleryFinal.OnHanlderResultCallback myResultCallBack=new GalleryFinal.OnHanlderResultCallback() {

        @Override
        public void onHanlderSuccess(int reqeustCode, final List<PhotoInfo> resultList) {

            waterDialog=new ProgressDialog(YxdAbstractPhtotoActivity.this);
            waterDialog.setMessage("图片处理中，请稍后");
            waterDialog.show();
            Thread t=new Thread(String.valueOf(Looper.getMainLooper())){
                @Override
                public void run() {
                    for (int i=0;i<resultList.size();i++) {
                        String path = resultList.get(i).getPhotoPath();
                        WindowManager winManager = getWindowManager();
                        DisplayMetrics metrics = new DisplayMetrics();
                        winManager.getDefaultDisplay().getMetrics(metrics);
                        Bitmap mBitmap = BitmapUtils.getBmpFromFile(path,
                                metrics.widthPixels, metrics.heightPixels, null);
                        try {
                            mBitmap.compress(Bitmap.CompressFormat.JPEG, 60, new FileOutputStream(path));
//                            int width = mBitmap.getWidth();
//                            int height = mBitmap.getHeight();
                            //加水印后的bitmap
                            //   Bitmap cropBitmap=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
                            // mBitmap = creatBitmap(mBitmap);
                            mBitmap=creatMyBitmap(mBitmap);
                            //将图片保存在本地指定路径
                            checkPhotoPathExist();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
                            Random random = new Random();
                            String fileName2 = String.valueOf(random.nextInt(Integer.MAX_VALUE));
                            newPhotoName = "yxd" + sdf.format(new Date()) + fileName2;
                            resultPath = pubClass.pictureSavePath + newPhotoName + ".jpg";
                            //流保存
                            File file = new File(resultPath);
                            FileOutputStream outputStream = null;
                            try {
                                outputStream = new FileOutputStream(file);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
                            try {
                                if (outputStream!=null){
                                    outputStream.flush();
                                    outputStream.close();
                                    mBitmap.recycle();
                                }
                                //保存图片后发送广播通知更新数据库
                                Uri uri = Uri.fromFile(file);
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                allPhotoFileString += resultPath + ",";

                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    Message msg=new Message();
                    msg.what=0;
                    mHandler.sendMessage(msg);

                }
            };
            t.start();

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(YxdAbstractPhtotoActivity.this,"图片获取失败",Toast.LENGTH_SHORT).show();
        }
    };
    //接收消息更新ui
    public static class iHandler extends Handler {

        private WeakReference<YxdAbstractPhtotoActivity> mActivity;
        iHandler(YxdAbstractPhtotoActivity activity){
            mActivity = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                //图片水印完毕
                mActivity.get().waterDialog.dismiss();
                mActivity.get().deleteDir();
            //    mActivity.get().setListViewData( mActivity.get().adapter,  mActivity.get().allPhotoFileString);
                mActivity.get().onPhotoSelected(mActivity.get().allPhotoFileString);
            }
        }
    }

    //由于第三方框架无法改变存储路径，因此将拍照保存的文件删除
    public void deleteDir(){
        //文件路径
        String path= Environment.getExternalStorageDirectory()+"/DCIM"+"/GalleryFinal";
        File file=new File(path);
        if (!file.exists() || !file.isDirectory()){
            return;
        }
        for (File dir:file.listFiles()){
            if (dir.isFile()){
                dir.delete();
            }else if (dir.isDirectory()){
                //递归删除
                deleteDir();
            }
            //删除目录
            file.delete();
        }
    }

    //绘制水印
    public Bitmap creatMyBitmap(Bitmap src){
//        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        int WW = metrics.widthPixels;
//        int WH = metrics.widthPixels;
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAlpha(60);
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap newBit=Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBit);
        canvas.drawBitmap(src,0,0,null);
        //创建一个矩形，将文字放入矩形中
        RectF rect=new RectF(30,h-160,450,h-30);
        canvas.drawRoundRect(rect,30,30,paint);
        //绘制文字
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setTextSize(36);
        paint.setAntiAlias(true);
        String date= BaseActivity.getNowDate();
        canvas.drawText(date,60,h-110,paint);
        canvas.drawText(shopName,60,h-65,paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newBit;
    }
    /**
     * 判断目录是否存在，不存在则创建改文件夹
     */
    public void checkPhotoPathExist() {

        File file = new File(pubClass.pictureSavePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    public abstract void onPhotoSelected(String resultPath);
    public abstract void onVideoRecode(String resultPath);


    private void methodRequiresPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            Log.i("yxdPermissions", "Already have permission!");
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "申请摄像头、录音、储存卡权限", PermissionUtil.CAMERA_STATE_REQUEST_CODE, perms);
        }
    }
    /*判断权限是否存在*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        /*
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
            Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
        }*/
    }



    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted
        Log.i("yxdPermissions", "onPermissionsGranted:" + requestCode + ":" + list.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        Log.i("yxdPermissions", "onPermissionsDenied:" + requestCode + ":" + list.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, list)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
